import {Component, Input, OnInit} from '@angular/core';
import {ReportService} from '../report.service';
import {StorageService} from '../../services/storage.service';
import {ConfirmationService, SelectItem} from 'primeng/primeng';
import {ActivatedRoute, Router} from '@angular/router';
import {MessageService} from "primeng/components/common/messageservice";
import {BasePage} from "../../base.page";

@Component({
  selector: 'app-history-report',
  templateUrl: './history-report.component.html',
  styleUrls: ['./history-report.component.scss']
})
export class HistoryReportComponent extends BasePage implements OnInit {
  dataSource;
  totalRecords;
  cols;
  zh;
  stacked = false;
  queryModel;
  historyReportModel = [];
  currentHistoryReport;
  showViewDetailMask: boolean = false; //报障详情
  showReportTreatment: boolean = false; //报障处理
  windowSize;
  chooseCids = [];
  selectMaterial = [];
  brands: SelectItem[];
  MaterialStatusData ;

  constructor(
    private reportService: ReportService,
    private storageService: StorageService,
    private router: Router,
    private route:ActivatedRoute,
    public confirmationService: ConfirmationService,
    public messageService:MessageService,


  ) {
    super(confirmationService,messageService)
  }

  ngOnInit() {
    this.brands = [
      { label: 'All Brands', value: null },
      { label: 'Audi', value: 'Audi' },
      { label: 'BMW', value: 'BMW' },
      { label: 'Fiat', value: 'Fiat' },
      { label: 'Honda', value: 'Honda' },
      { label: 'Jaguar', value: 'Jaguar' },
      { label: 'Mercedes', value: 'Mercedes' },
      { label: 'Renault', value: 'Renault' },
      { label: 'VW', value: 'VW' },
      { label: 'Volvo', value: 'Volvo' }
    ];
    this.zh = {
      firstDayOfWeek: 1,
      dayNames: [ '周一', '周二', '周三', '周四', '周五', '周六', '周日' ],
      dayNamesShort: [ '一', '二', '三', '四', '五', '六', '七' ],
      dayNamesMin: [ '一', '二', '三', '四', '五', '六', '七' ],
      monthNames: [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
      monthNamesShort: [ '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二' ],
    };

    this.windowSize = window.innerWidth;
    if (this.windowSize < 1024){
      this.stacked = true;
    }
    this.cols = [
      {field: 'fault_type', header: '故障所属'},
      {field: 'people', header: '报障人'},
      {field: 'time', header: '报障时间'},
      {field: 'location', header: '故障位置'},
      {field: 'status', header: '状态'},
      {field: 'handle_people', header: '处理人'},
      {field: 'handle_datetime', header: '完成时间'},
    ];
    this.queryModel = {
        'id': '',
        'people': '',
        'fault_type': '',
        'status': '',
        'time_start': '',
        'time_end': '',
        'handle_people': '',
    };
    this.queryReport();
    this.queryReportStatusDate();
  }
  //查询历史报障
  queryReport(){
        this.reportService.getHistoryReport(this.queryModel).subscribe(data => {
          this.dataSource = data ? data : [];
          console.log(this.dataSource);
          for (let i = 0 ; i < this.dataSource.length; i++){
            let devices = this.dataSource[i]['devices'] ? this.dataSource[i]['devices'] : [];
            this.dataSource[i]['showdevices'] = [];
            for (let j = 0; j < devices.length; j++){
              let temp = devices[j]['ano'];
              this.dataSource[i]['showdevices'].push(temp);
            }
            this.dataSource[i]['showdevices'].join(';');
        }

          console.log(this.dataSource);
          this.totalRecords = this.dataSource.length;
          this.historyReportModel = this.dataSource.slice(0, 10);
      });
  }
  clearSearch() {
    this.queryModel.fault_type = '';
    this.queryModel.people = '';
    this.queryModel.time_start = '';
    this.queryModel.time_end = '';

  }
  suggestInsepectiones(){
    this.queryReport();
  }
  //查看详情
  showReport(report){
    this.currentHistoryReport = report;
    console.log(this.currentHistoryReport);
    this.showViewDetailMask = !this.showViewDetailMask;
  }
  closeViewDetail(bool){
    this.showViewDetailMask = bool;
  }
  //故障处理model
  showReportTreatmentMask(report){
    this.storageService.setReportId('reportid', report.id);
    this.showReportTreatment = !this.showReportTreatment;
    this.currentHistoryReport = report;
  }
  closeReportTreamentMask(bool){
    this.showReportTreatment = bool;
  }
  display: boolean = false;
  loadCarsLazy(event) {
    setTimeout(() => {
      if (this.dataSource) {
        this.historyReportModel = this.dataSource.slice(event.first, (event.first + event.rows));
      }
    }, 250);
  }
  //更改处理后的历史报障
  updatehistoryReportModel(){
    this.queryReport();
  }
  onOperate(report) {
    this.currentHistoryReport = report;
    this.showViewDetailMask = !this.showViewDetailMask;
  }
  queryReportStatusDate(){
    this.reportService.getStatusReport().subscribe(data=>{
      if(!data){
        this.MaterialStatusData = [];
      }else{
        this.MaterialStatusData = data;
        this.MaterialStatusData = this.reportService.formatDropdownData(this.MaterialStatusData)
      }
    });
  }
  updateOption(current){
    let cid = current['cid'];
    this.router.navigate(['../review'],{queryParams:{cid:cid,state:'update',title:'编辑'},relativeTo:this.route})
  }

  deleteReport(current){
    let cid = current['cid'];
    //请求成功后删除本地数据
    this.confirm('确认删除吗?',()=>{this.deleteoption(cid)});
  }
  deleteoption(cid){
    this.reportService.deleteReport(cid).subscribe(()=>{
      this.queryReport();
      this.alert('删除成功')
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===0||JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，请联系管理员或稍后重试'
      }else{
        message = err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  }
}
